package com.ych.DemoSSM.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;

public class HttpClientUtil {

    private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    /**
     * post请求
     *
     * @param url            url地址
     * @param params         参数
     * @param noNeedResponse 不需要返回结果
     * @return
     */
    public static String httpPost(String url, Map<String, Object> params, boolean noNeedResponse) throws Exception {
        logger.debug(Thread.currentThread().getName() + ":" + url);

        String ret = "";
        // post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != params) {
                // 解决中文乱码问题
                String jsonParam = JSON.toJSONString(params);
                logger.debug(Thread.currentThread().getName() + ":" + jsonParam);

                StringEntity entity = new StringEntity(jsonParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /** 请求发送成功，并得到响应 **/
            if (result.getStatusLine().getStatusCode() == 200) {
                try {
                    /** 读取服务器返回过来的json字符串数据 **/
                    ret = EntityUtils.toString(result.getEntity());
                    logger.debug(Thread.currentThread().getName() + ":" + ret);
                    if (noNeedResponse) {
                        return null;
                    }
                    /** 把json字符串转换成json对象 **/
                    // jsonResult = JSONObject.fromObject(str);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            } else {
                throw new Exception("POST请求失败:" + result.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

        return ret;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static String httpGet(String url) {
        logger.debug(Thread.currentThread().getName() + ":" + url);
        String ret = "";
        // get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            // 发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数据 **/
                ret = EntityUtils.toString(response.getEntity());
                logger.debug(Thread.currentThread().getName() + ":" + ret);
                /** 把json字符串转换成json对象 **/
                // jsonResult = JSONObject.fromObject(strResult);
            } else {
                System.err.println("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}
